package com.itheima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.article.feign.ApAuthorFeign;
import com.itheima.article.pojo.ApAuthor;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.dto.PageRequestDto;
import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import com.itheima.user.dto.ApUserRealnamePageRequestDto;
import com.itheima.user.mapper.ApUserMapper;
import com.itheima.user.pojo.ApUser;
import com.itheima.user.pojo.ApUserRealname;
import com.itheima.user.mapper.ApUserRealnameMapper;
import com.itheima.user.service.ApUserRealnameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.wemedia.feign.WmUserFeign;
import com.itheima.wemedia.pojo.WmUser;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServlet;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @description <p>APP实名认证信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.user.service.impl
 */
@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    private WmUserFeign userFeign;

    @Autowired
    private ApAuthorFeign apAuthorFeign;

    @Autowired
    private ApUserMapper apUserMapper;


    @Override
    public ResultVo<ApUserRealname> findPage(ApUserRealnamePageRequestDto dto) {

        //创建分页对象
        IPage<ApUserRealname> pageInfo = new Page<ApUserRealname>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<ApUserRealname> lwq = Wrappers.<ApUserRealname>lambdaQuery()
                .eq(null != dto.getStatus(), ApUserRealname::getStatus, dto.getStatus());

        page(pageInfo, lwq);


        return PageResultVo.pageResult(dto.getPage(), dto.getSize(), pageInfo.getTotal(), pageInfo.getRecords());
    }


    /**
     * 实名审核驳回
     *
     * @param paramMap
     */
    @Override
    public void authFail(Map<String, Object> paramMap) {
        //1.获取对象
        Integer keyId = (Integer) paramMap.get("id");
        String reason = (String) paramMap.get("msg");

        //2.构建更新的对像
        ApUserRealname pojo = new ApUserRealname();
        pojo.setReason(reason);
        pojo.setId(keyId);
        pojo.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_REJECT);
        pojo.setUpdatedTime(LocalDateTime.now());

        //3.更新
        updateById(pojo);
    }

    /**
     * 审核 - 通过
     * 定位问题：看日志：linux    tail -f 文件名 /实名认证 N下一个. 把日志文件下载到本地
     *
     * @param paramMap
     */

    @Transactional(rollbackFor = Throwable.class)
    @GlobalTransactional
    @Override
    public void authPass(Map<String, Object> paramMap) {

        //1. 参数校验
        Integer id = (Integer) paramMap.get("id"); //-100
        log.debug("实名认证：id={}", id);
        if (null == id) {
            throw new LeadNewsException("参数异常");
        }
        //2. 更新实名认证的状态 update table set .... where id=-100; 0
        ApUserRealname pojo = new ApUserRealname();
        pojo.setId(id);
        pojo.setUpdatedTime(LocalDateTime.now());
        pojo.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_PASS);
        updateById(pojo);
        log.debug("实名认证更新认证状态：id={}", id);
        //3. 更新用户信息，认证通过、flag为自媒体人
        // 前端传来的id不是用户的id, 通过查询实名认证信息，得到真正的用户id
        ApUserRealname userRealname = getById(id); // -100
        if (null == userRealname) {
            throw new LeadNewsException("参数异常");
        }
        Integer appUserId = userRealname.getUserId();
        // 更新用户信息
        ApUser apUser = new ApUser();
        apUser.setId(appUserId);
        // 已经认证过
        apUser.setIsIdentityAuthentication(BusinessConstants.ApUserConstants.AUTHENTICATED);
        // 从普通用户升级为自媒体人
        apUser.setFlag(BusinessConstants.ApUserConstants.FLAG_WEMEDIA);
        apUserMapper.updateById(apUser);
        log.debug("实名认证 从普通用户升级为自媒体人：id={}, appUserId={}", id, appUserId);

        //通过appUserId查询用户信息
        ApUser appUserInfo = apUserMapper.selectById(appUserId);

        //TODO 4. 远程调用(自媒体微服务)创建自媒体账号
        // 1. 添加feign依赖
        // 2. 消费者端创建接口 类上注解、方法(提供方的controller的方法): 路径完整，取别名
        // 3. 消费者端 扫包 调用 注入
        // 4.1 通过appUserId查询这个自媒体账号，
        Integer wmUserId = addWmUser(appUserId, appUserInfo);
        log.debug("实名认证 添加自媒体账号成功：id={}, appUserId={}, wmUserId={}", id, appUserId, wmUserId);
        //TODO 5. 远程调用创建(文章微服务)作者账号
        addApAuthor(wmUserId, appUserInfo);
        log.debug("实名认证 添加作者账号成功：id={}, appUserId={}, wmUserId={}", id, appUserId, wmUserId);
        //6. 事务控制

    }


    /**
     * 添加作者信息
     *
     * @param wmUserId
     * @param appUserInfo
     */
    private void addApAuthor(Integer wmUserId, ApUser appUserInfo) {
        //1. 查询作者是否存在
        //1.1 远程调用文章微服务查询
        ResultVo<ApAuthor> getResult = apAuthorFeign.getByApUserIdWmUserId(appUserInfo.getId(), wmUserId);
        //1.2 查询结果isSuccess不为true，失败要报错
        if (!getResult.isSuccess()) {
            throw new LeadNewsException("调用文章微服务 查询作者信息失败");
        }
        //1.3 获取返回的数据
        ApAuthor author = getResult.getData();
        //2. 不存在则添加作者信息
        if (null == author) {
            //2.1 构建作者pojo对象
            author = new ApAuthor();
            //2.2 pojo设置属性值
            author.setName(appUserInfo.getName());
            author.setType(BusinessConstants.ApAuthorConstants.A_MEDIA_USER);
            author.setUserId(appUserInfo.getId());
            author.setWmUserId(wmUserId);
            author.setCreatedTime(LocalDateTime.now());
            //2.3 远程调用添加
            ResultVo addResult = apAuthorFeign.add(author);
            //2.4 对添加结果判断，如果失败则报错
            if (!addResult.isSuccess()) {
                throw new LeadNewsException("调用文章微服务 添加作者信息失败");
            }
        }
    }

    /**
     * 添加自媒体账号
     *
     * @param appUserId
     * @param appUserInfo
     * @return
     */
    private Integer addWmUser(Integer appUserId, ApUser appUserInfo) {
        ResultVo<WmUser> wmUserResult = userFeign.getByApUserId(appUserId);
        if (!wmUserResult.isSuccess()) {
            throw new LeadNewsException("调用自媒体微服务失败");
        }
        WmUser wmUser = wmUserResult.getData();
        // 4.2 如果不存在添加
        if (null == wmUser) {
            //4.3 创建自媒体账号
            wmUser = new WmUser();
            BeanUtils.copyProperties(appUserInfo, wmUser);
            wmUser.setId(null);
            wmUser.setApUserId(appUserId);
            wmUser.setNickname(appUserInfo.getName());
            wmUser.setType(BusinessConstants.WmUserConstants.TYPE_PERSONAL);
            wmUser.setStatus(BusinessConstants.WmUserConstants.STATUS_OK);
            wmUser.setCreatedTime(LocalDateTime.now());
            ResultVo<WmUser> insertResult = userFeign.insert(wmUser);
            if (!insertResult.isSuccess()) {
                // 添加自媒体失败了
                throw new LeadNewsException("调用自媒体微服务添加账号失败");
            }
            // 为什么???
            wmUser = insertResult.getData();
        }
        return wmUser.getId();
    }
}